package com.example.pandaso.filter;

import com.example.pandaso.utils.JwtUtils;
import com.example.pandaso.utils.ResponseUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
@WebFilter(urlPatterns = "/api/*")
public class GlobalFilter implements Filter {
    @Autowired
    private JwtUtils jwtUtils;

    private List<String> excludePatterns = Arrays.asList("/api/login", "/api/tips/google",
            "/api/tips/baidu", "/api/tips/bing", "/api/tips/sougou", "/api/tips/360",
            "/api/tips/scholar", "/api/tips/yahoo", "/api/tips/duckduckgo", "/api/enroll","/api/getTop"
            ,"/api/addTop","/api/starClick");

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        if (excludePatterns.contains(requestURI)) {
            chain.doFilter(request, response);
        } else {
            // 获取请求头中的token
            String token = httpRequest.getHeader("token");
            if (token == null || token.isEmpty()) {
                // 如果token为空，则返回未授权的响应
                ResponseUtils.error((HttpServletResponse) response, HttpStatus.UNAUTHORIZED, "未授权");
            } else {
                // 解析JWT令牌，获取用户名
                String username = jwtUtils.getUsernameFromToken(token);
                if (username == null) {
                    // 如果解析失败，则返回未授权的响应
                    ResponseUtils.error((HttpServletResponse) response, HttpStatus.UNAUTHORIZED, "未授权");
                } else {
                    // 验证token
                    Boolean isOverdue = jwtUtils.validateToken(token, username);
                    if (!isOverdue) {
                        // 如果token过期，则返回token过期的响应
                        ResponseUtils.error((HttpServletResponse) response, HttpStatus.UNAUTHORIZED, "未授权");
                    } else {
                        // 放行
                        chain.doFilter(request, response);
                    }
                }
            }
        }
    }

}
